<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Reg extends MY_Controller {

	public function __construct(){
		parent::__construct();
		$this->CI = & get_instance (); // 调用CI核心对象
		$this->CI->load->library ( 'session' );
	}
	public function index()
	{
		$callback = $this->input->get("callback");
		$username = $this->input->get("username");
		$password = $this->input->get("password");
		$pwd = $this->input->get("pwd");
		
		if($password!=$pwd){
			$msg = "密码两次输入不一致";
			$code = 4002;
		}else{
			$res = $this->checkUser($username);
			if($res){
				$re = $this->addUser($username,$password);
				if($re){
					$msg = "注册成功";
					$code = 4000;
				}else{
					$msg = "注册失败";
					$code = 4003;
				}
			}else{
				$msg = "你输入的用户名已存在";
				$code = 4001;
			}
		}
		
		$result = array(
			"msg" => $msg,
			"code" => $code
		);
		
		$result_json = json_encode($result);
		echo $callback."($result_json)";
	}
	
	public function checkUser($username){
		$sql = "select *  from future_u_c_user where username = '{$username}'";
		$re = $this->db->query($sql)->row_array();
		if(empty($re)){
			return true;
		}else{
			return false;
		}
	}
	
	public function addUser($username,$password){
		$data['username'] = $username;
		$data['password'] = $this->_encrypt($password);
		
		$re = $this->db->insert("future_u_c_user",$data);
		
		if($re){
			return true;
		}else{
			return flase;
		}
	}
	/**
	 * 密码加密
	 */
	private function _encrypt($str) {
		$this->load->library ( 'encrypt' );
		$re = $this->encrypt->encode ( $str );
		return $re;
	}
}